<template>
  <div class="wrapper" ref="scrollcontainer" v-infinite-scroll="load" infinite-scroll-disabled="disabled" infinite-scroll-immediate="false">
    <div v-if="!showSectionSelection" class="top-bar">
      <div v-if="sectionType === 'home'" class="time-select-btn" @click="openTimeSelect">
        {{timeName? timeName: '发布时间'}}<i class="el-icon-caret-bottom"></i>
      </div>
      <div v-if="sectionType === 'regular'" class="time-select-btn" @click="openSectionSelect">
        {{sectionPathName}}<i class="el-icon-caret-bottom"></i>
      </div>
      <div v-if="sectionType === 'home'" class="search-btn">
        <input type="text" @focus="hiddenTab" @blur="showTab" class="mobile-input" placeholder="搜索" v-model="searchKey" @change="searchItem(true)">
      </div>
      <div v-if="sectionType === 'regular' || sectionType === 'personal'" class="section-list">
        <div class="section-wrapper clearfix" :style="{'width': sectionWidth + 'px'}">
          <div v-for="section in sectionList" :key="section.id" @click="changeSection(section.id, section)" :class="{'active': currentSectionId === section.id}">{{section.sectionName}}</div>
        </div>
      </div>
    </div>
    <div v-if="showSectionSelection" style="border-top: 1px solid #e8e8e8;">
      <div class="folder-item" v-for="item in pathArr" :key="item.id" @click="openNextPath(item)">
        <img src="../../../../assets/img/lanmu.png" alt="">{{item.sectionName}}
      </div>
    </div>
    <div v-if="!showSection && !showSectionSelection" class="article-list">
      <div v-for="(article, idx) in articleList" :key="article.id" class="article-item" @click="openArticle(article.contextId? article.contextId : article.id)">
        <h2 class="article-title">
          <img v-if="sectionType === 'home' && idx < 3 && article.articleReviewCount >= 10" src="../../../../assets/img/hot.png" alt="" style="width: 14px;position:relative;top: -2px;">
          <img v-if="sectionType === 'home' && idx < 3 && article.articleReviewCount >= 10" src="../../../../assets/img/hot.png" alt="" style="width: 14px;position:relative;top: -2px;">
          <img v-if="sectionType === 'home' && idx < 3 && article.articleReviewCount >= 10" src="../../../../assets/img/hot.png" alt="" style="width: 14px;position:relative;top: -2px;">
          {{article.articleTitle || article.contextTitle}}
        </h2>
        <div class="article-desc">{{article.articleInfo || article.contextInfo}}</div>
        <div class="article-from clearfix">
          <span v-if="article.plateId === '0'" style="color:red;position:relative;top:2px;left:2px;"><svg aria-hidden="true" style="font-size:14px;" class="site-sidebar__menu-icon icon-svg icon-svg__annouce"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-annouce"></use></svg></span>
          <span v-if="article.plateId === '1'" style="color:#0286e2;position:relative;top:2px;left:2px;"><svg aria-hidden="true" style="font-size:14px;" class="site-sidebar__menu-icon icon-svg icon-svg__library"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-library"></use></svg></span>
          <span v-if="article.plateId === '2'" style="color:#00b853;position:relative;top:2px;left:2px;"><svg aria-hidden="true" style="font-size:14px;" class="site-sidebar__menu-icon icon-svg icon-svg__discussion"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-discussion"></use></svg></span>
          <span v-if="article.plateId === '3'" style="color:#ebb563;position:relative;top:2px;left:2px;"><svg aria-hidden="true" style="font-size:14px;" class="site-sidebar__menu-icon icon-svg icon-svg__tixing"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-tixing"></use></svg></span>
          {{article.plateName}}>{{article.firstSectionName}}{{article.secondSectionId? '>'+article.secondSectionName: ''}}
          <div v-if="sectionType === 'personal'" class="action-btn">
            <span v-if="article.articleStatus === '1' || article.articleStatus === '0'" @click.stop="editArticle(article.id)" style="margin-right: 15px;"><i class="el-icon-edit"></i>编辑</span>
            <span v-if="article.articleStatus === '1' || article.articleStatus === '0'" @click.stop="delArticle(article.id)"><i class="el-icon-delete"></i>删除</span>
            <span v-if="article.articleStatus === '2'" @click.stop="rebackArticle(article.id)" style="margin-right: 15px;"><i class="el-icon-document-checked"></i>恢复</span>
            <span v-if="article.articleStatus === '2'" @click.stop="managerDel(article.id)"><i class="el-icon-document-delete"></i>彻底删除</span>
          </div>
          <div v-if="sectionType !== 'personal' || currentSectionId === '-100'" class="action-btn">
            {{article.articleMasterName || article.contextMasterName}}, {{article.articleModifytime || article.contextModifytime}}
          </div>
        </div>
      </div>
      <p v-if="loading">加载中...</p>
      <p v-if="noMore">没有更多了</p>
    </div>
    <div v-if="showSection && !showSectionSelection" class="module-list">
      <div v-for="moduleItem in moduleList" :key="moduleItem.id" class="module-item" @click="editSection(moduleItem.id)">
        {{moduleItem.sectionName}}<span v-if="moduleItem.sectionLevel === 0" style="color:red;">(版块)</span>
        <span v-if="moduleItem.sectionLevel === 1" style="color:red;">({{getModule(moduleItem.sectionParentId)}})</span>            
        <span v-if="moduleItem.sectionLevel === 1" @click.stop="removeItem(moduleItem)" style="position:absolute; top: 0px; right: 20px;"><i class="el-icon-delete"></i>删除</span>
      </div>
    </div>
    <div v-if="showTabStatus" class="component-tabbar" :style="{'paddingBottom': bottomBarHeight + 'px'}">
      <div class="tab" @click="changeTab('mbbs-home')">
        <img v-if="sectionType !== 'home'" src="../../../../assets/mobile/home.png" alt="">
        <img v-if="sectionType === 'home'" src="../../../../assets/mobile/home_selected.png" alt="">
        <p :class="{'active': sectionType === 'home'}">首页</p>
      </div>
      <div class="tab" @click="changeTab('mbbs-announcement')">
        <img v-if="moduleId !== '0'" src="../../../../assets/mobile/annouce.png" alt="">
        <img v-if="moduleId === '0'" src="../../../../assets/mobile/annouce_selected.png" alt="">
        <p :class="{'active': moduleId === '0'}">公告</p>
      </div>
      <div class="tab" @click="changeTab('mbbs-library')">
        <img v-if="moduleId !== '1'" src="../../../../assets/mobile/library.png" alt="">
        <img v-if="moduleId === '1'" src="../../../../assets/mobile/library_selected.png" alt="">
        <p :class="{'active': moduleId === '1'}">文库</p>
      </div>
      <div class="tab" @click="changeTab('mbbs-discussion')">
        <img v-if="moduleId !== '2'" src="../../../../assets/mobile/discussion.png" alt="">
        <img v-if="moduleId === '2'" src="../../../../assets/mobile/discussion_selected.png" alt="">
        <p :class="{'active': moduleId === '2'}">讨论</p>
      </div>
      <div class="tab" @click="changeTab('mbbs-unnormal')">
        <img v-if="moduleId !== '3'" src="../../../../assets/mobile/unnormal.png" alt="">
        <img v-if="moduleId === '3'" src="../../../../assets/mobile/unnormal_selected.png" alt="">
        <p :class="{'active': moduleId === '3'}">异常</p>
      </div>
      <div class="tab" @click="changeTab('mbbs-personal')">
        <img v-if="sectionType !== 'personal'" src="../../../../assets/mobile/personal.png" alt="">
        <img v-if="sectionType === 'personal'" src="../../../../assets/mobile/personal_selected.png" alt="">
        <p :class="{'active': sectionType === 'personal'}">我的</p>
      </div>
    </div>
  </div>
</template>

<script>
import dingMixin from  '@/mixins/ding'
import {dateUtil} from '@/utils/dateUtil'

export default {
  data() {
    return {
      showArticle: false,
      articleList: [],
      searchKey: '',
      currentArticleId: '',
      pageSize: 15,
      page:1,
      totalPage: 2,
      currentSectionId: '',
      sectionList: [],
      timeName: '',
      articleStartTime: '',
      articleEndtime: '',
      showEditor: false,
      isModuleManager: false,
      isSectionManager: false,
      sectionWidth: 0,
      timeArr: ['最近三天','最近一周','最近一个月','全部'],
      bottomBarHeight: 5,
      showSection: false,
      moduleList: [],
      modules: [],
      loading: false,
      isFirstLoading: true,
      isLeave: false,
      showTabStatus: true,
      showSectionSelection: false,
      pathArr: [],
      currentScrollTop: 0
    }
  },
  mixins: [dingMixin],
  props: ['sectionType', 'moduleId'],
  computed: {
    noMore () {
      return this.page > this.totalPage;
    },
    disabled () {
      return this.isFirstLoading || this.loading || this.noMore || this.isLeave
    },
    isBBSManager() {
      return this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1250299091356758017')
    }
  },
  async mounted() {
    this.mobileGetDevice(({model, brand, version}) => {
      if(brand === 'iPhone' && ( model.indexOf('10') > 0 || model.indexOf('11') > 0)) {
        this.bottomBarHeight = 30;
      }
    })
    let modules = await this.$httpN.postQ('community/section/list', {'parentid': null});
    modules.forEach((moduleItem) => {
      if(moduleItem.id === this.moduleId){
        let managerArr = moduleItem.sectionManageUserid.split(',');
        this.isModuleManager = managerArr.includes(this.userInfo.dingId);
      }
    })
    this.modules = modules;
    if(this.sectionType === 'personal') {
      let sectionWidth = 0;
      this.sectionList = await this.$httpN.postQ('community/section/list', {'parentid': null})
      this.sectionList.unshift({sectionName: '我的收藏', id: '-100'})
      this.sectionList.push({sectionName: '草稿箱', id: '-98'})
      this.sectionList.push({sectionName: '回收站', id: '-99'})
      this.sectionList.forEach(item => {
        sectionWidth += item.sectionName.length * 15;
        sectionWidth += 20;
      })
      this.sectionWidth = sectionWidth;

      this.currentSectionId = this.sectionList[0].id;
    }

    if(this.sectionType === 'regular') {
      this.openSectionSelect()
    }

    if(this.sectionType === 'home' || this.sectionType === 'personal'){
      await this.searchItem(true);
    }

    if(this.sectionType === 'home') {
      let articleId = this.$route.params.id;
      if(articleId) this.openArticle(articleId);
    }

  },
  activated() {
    this.isLeave = false;
    if(this.sectionType === 'personal' && this.showSection){
      this.mobileSetRightMenu([{id: 'add', text: '添加栏目'}], (directive) => {
        if(directive === 'add'){
          this.$router.push({ name: 'mbbs-module'})
        }
      });
    }
    if(window.MOBILE_NEEDREFRESH) {
      window.MOBILE_NEEDREFRESH = false;
      this.refresh();
    }else {
      this.$refs.scrollcontainer.scrollTop = this.currentScrollTop;
    }

    this.mobildPullToRefresh(this.refresh);
  },
  deactivated() {
    this.isLeave = true;
  },
  methods: {
    saveHeight() {
      this.currentScrollTop = this.$refs.scrollcontainer.scrollTop;
      this.mobileStopRefresh()
    },
    async openSectionSelect() {
      this.showSectionSelection = true;
      let data = await this.$httpN.postQ('community/section/list', {'parentid': this.moduleId})
      if(data.length > 0) {
        data = data.filter((item) => {
          if(item.sectionUserid !== '') {
            let managerArr = item.sectionManageUserid.split(',');
            let userArr = item.sectionUserid.split(',');
            if(item.sectionRange === '0' || managerArr.includes(this.userInfo.dingId) || this.isModuleManager) {
              return true;
            }else {
              return userArr.includes(this.userInfo.dingId);
            }
          }else{
            return true;
          }
        })
      }
      this.pathArr = data;
    },
    async openNextPath(item) {
      this.sectionPathName = item.sectionName;
      this.sectionPathId = item.id;
      let managerArr = item.sectionManageUserid.split(',');
      this.isSectionManager = managerArr.includes(this.userInfo.dingId);
      let data = await this.$httpN.postQ('community/section/list', {'parentid': item.id})
      if(data.length > 0) {
        data = data.filter((item) => {
          if(item.sectionUserid !== '') {
            let managerArr = item.sectionManageUserid.split(',');
            let userArr = item.sectionUserid.split(',');
            if(item.sectionRange === '0' || managerArr.includes(this.userInfo.dingId) || this.isModuleManager || this.isSectionManager) {
              return true;
            }else {
              return userArr.includes(this.userInfo.dingId);
            }
          }else{
            return true;
          }
        })
      }
      
      let sectionWidth = 0;
      this.sectionList = data;
      this.sectionList.forEach(item => {
        sectionWidth += item.sectionName.length * 15;
        sectionWidth += 20;
      })
      this.sectionWidth = sectionWidth;
      this.articleList = [];
      this.currentSectionId = '';
      if(this.sectionList.length > 0) this.currentSectionId = this.sectionList[0].id;
      this.showSectionSelection = false;
      await this.searchItem(true)

    },
    removeItem(item) {
      this.mobileConfirm('此操作将永久删除栏目, 是否继续?', async ()=> {
        if(!await this.$httpN.postQ('community/section/delete', {id: item.id}, false)) return;
        this.mobileMessage('删除成功');
        this.searchModuleList();
      })
    },
    hiddenTab() {
      this.showTabStatus = false;
    },
    showTab() {
      this.showTabStatus = true;
    },
    refresh() {
      if(this.currentSectionId !== '-101'){
        this.searchItem(true)
      }else {
        this.searchModuleList();
      }
    },
    getModule(id) {
      let moduleName = '';
      this.modules.every((item) => {
        if(item.id !== id) return true;
        moduleName = item.sectionName;
        return false
      })
      return moduleName
    },
    load () {
      this.loading = true;
      this.page ++;
      this.searchItem();
    },
    editSection(id) {
      this.$router.push({ name: 'mbbs-module', params: {id}})
    },
    editArticle(id) {
      this.$router.push({ name: 'mbbs-editor', params: {id}})
    },
    rebackArticle(id) {
      this.mobileConfirm('此操作将恢复文章并保存到草稿箱, 是否继续?', async ()=> {
        if(!await this.$httpN.postB('community/article/recycle', {ids: id, articleStatus: 0})) return;
        this.mobileMessage('恢复成功');
        this.searchItem(true)
      })
    },
    delArticle(id) {
      this.mobileConfirm('此操作将删除文章到回收站, 是否继续?', async ()=> {
        if(!await this.$httpN.postB('community/article/recycle', {ids: id, articleStatus: 2})) return;
        this.mobileMessage('删除成功');
        this.searchItem(true)
      })
    },
    managerDel(id) {
      this.mobileConfirm('此操作将永久删除该文章, 是否继续?', async ()=> {
        if(!await this.$httpN.postB('community/article/delete', {ids: id})) return;
        this.mobileMessage('删除成功');
        this.searchItem(true)
      })
    },
    changeTab(tab) {
      if(this.sectionType === 'home') {
        this.$router.push({ name: tab })
      }else if(tab === 'mbbs-home'){
        this.$router.go(-1);
      }else {
        this.$router.replace({ name: tab })
      }
    },
    async searchItem(init) {
      if(init) {
        this.page = 1;
        this.articleList = [];
        this.isFirstLoading = true;
      }
      let data;
      if(this.sectionType === 'regular' || this.sectionType === 'home'){
        if(this.sectionType === 'regular' && this.currentSectionId === '') return;
        if(this.searchKey) {
          data = await this.$httpN.postB('community/article/search', {
            page: this.page,
            limit: this.pageSize,
            sectionId: this.sectionType === 'home' ? '' :this.moduleId,
            isHomeSearch: this.sectionType === 'home' ? '1' :'',
            articleSearch: this.searchKey,
            articleStatus: 1
          })
        }else {
          data = await this.$httpN.postB('community/article/list', {
            page: this.page,
            limit: this.pageSize,
            sectionId: this.currentSectionId,
            articleStartTime: this.articleStartTime,
            articleEndtime: this.articleEndtime,
            isHomeSearch: this.sectionType === 'home' ? '1' :'',
            articleStatus: 1
          })
        }
      }else if(this.currentSectionId === '-100') {
        data = await this.$httpN.postB('community/likecollection/list', {
          page: this.page,
          limit: this.pageSize,
          userId: this.userInfo.dingId,
          dataType: 1
        })
      }else if(this.sectionType === 'personal') {
        data = await this.$httpN.postB('community/article/userList', {
          page: this.page,
          limit: this.pageSize,
          sectionId: this.currentSectionId === '-99' || this.currentSectionId === '-98'? '': this.currentSectionId,
          articleStatus: this.currentSectionId === '-99'? '2': this.currentSectionId === '-98'? '0': '1'
        })
      }

      this.articleList.push(...data.list);

      this.totalPage = data.totalPage;
      this.loading = false;
      if(init) {
        this.$nextTick(() => {
          this.isFirstLoading = false;
        })
      }
    },
    async searchModuleList(init) {
      if(init) this.page = 1;
      let data = await this.$httpN.postQ('community/section/list', {'parentid': this.parentid ? this.parentid: 'all'})
      this.moduleList = data;
    },
    changeSection(id, section) {
      if(id === '-101'){
        this.mobileSetRightMenu([{id: 'add', text: '添加栏目'}], (directive) => {
          if(directive === 'add'){
            this.$router.push({ name: 'mbbs-module'})
          }
        });
        this.currentSectionId = id;
        this.searchModuleList();
        this.showSection = true;
        return;
      }
      if(this.sectionType === 'personal' && this.showSection && id !== '-101'){
        this.mobileSetRightMenu([{id: 'save', text: '写文章'}], (directive) => {
          if(directive === 'save'){
            this.$router.push({ name: 'mbbs-editor'})
          }
        });
      }
      this.showSection = false;
      if(this.sectionType === 'regular') {
        let managerArr = section.sectionManageUserid.split(',');
        this.isSectionManager = managerArr.includes(this.userInfo.dingId);
      }
      
      this.currentSectionId = id;
      this.searchItem(true);
    },
    openTimeSelect() {
      this.mobileSelect('选择发布时间',this.timeArr,({buttonIndex}) => {
        this.timeName = this.timeArr[buttonIndex];
        this.selectTime();
      })
    },
    selectTime() {
      let e = this.timeName;
      this.articleEndtime = dateUtil.thisDay() + ' 23:59:59';
      if(e === '最近三天') {
        this.timeName = '最近三天';
        this.articleStartTime = dateUtil.nDaysBefore(3);
      }else if(e === '最近一周'){
        this.timeName = '最近一周';
        this.articleStartTime = dateUtil.nDaysBefore(7);
      }else if(e === '最近一个月'){
        this.timeName = '最近一个月';
        this.articleStartTime = dateUtil.nDaysBefore(30);
      }else {
        this.articleEndtime = '';
        this.articleStartTime = '';
      }
      this.searchItem(true)
    },
    openMobileInput() {
      this.mobileInput('请输入搜索内容', this.searchKey, ({text}) => {
        this.searchKey = text;
        this.searchItem(true);
      })

    },
    openArticle(id) {
      if(this.sectionType === 'personal' && (this.currentSectionId === '-98' || this.currentSectionId === '-99')) return;
      this.$router.push({ name: 'mbbs-article', params: {id}})
    }
  }
}
</script>

<style lang="scss" scoped>
  .top-bar{
    line-height: 44px;
    top: 0;
    left: 0;
    width: 100%;
    border-bottom: 1px solid #e8e8e8;
    padding: 0 10px;
    display: flex;
    background: #FFF;
    z-index: 99;
    .search-btn{
      flex:1;
      padding-left:15px;
      position: relative;
      .mobile-input{
        width: 100%;
        border: 1px solid #DCDFE6;
        line-height: 20px;
        height: 30px;
        outline: none;
        -webkit-appearance: none;
        font-size:12px;
        border-radius: 4px;
        padding: 0 15px;
      }
    }
    .section-list{
      flex:1;
      overflow-x: scroll;
      padding-left: 10px;
      .section-wrapper{
        div{
          margin-right: 20px;
          float:left;
        }
        .active{
          color: #42A5F5;
          font-weight: bold;
          font-size: 15px;
        }
      }
    }
  }
  .wrapper{
    background: #F6F6F6;
    height: 100vh;
    // padding-top: 44px;
    padding-bottom: 80px;
    overflow: auto;
  }
  .article-list{
    >p{
      margin: 0;
      color: #999;
      text-align: center;;
      margin-top: 20px;
    }
  }
  .article-item{
    padding: 12px;
    background: #FFF;
    margin-bottom: 10px;
    .article-title{
      font-size: 14px;
      font-weight: bold;
      margin: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    .article-author{
      margin-top: 5px;
      font-size: 12px;
      font-weight: 500;
    }
    .article-desc{
      margin-top: 5px;
      font-size: 13px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    .article-from{
      margin-top: 5px;
      font-size: 12px;
      position: relative;
      .icon-svg {
        width: 1em;
        height: 1em;
        fill: currentColor;
      }
      .action-btn{
        position: absolute;
        right: 0;
        top:4px;
        color: #999;
      }
    }
  }
  .component-tabbar{
    position:fixed;
    bottom:0;
    left: 0;
    width: 100%;
    padding: 5px 0;
    text-align: center;
    background: #FFF;
    box-shadow: 0 0 10px 0 hsla(0,6%,58%,.6);
    z-index: 99;
    display: flex;
    .tab{
      flex: 1;
      padding-top: 2px;
      img{
        width: 6vw;
      }
      p{
        margin: 0;
        color: #969696;
        &.active{
          color: #42A5F5;
        }
      }
    }
  }
  .module-item{
    background: #FFF;
    text-align: center;
    height: 50px;
    line-height: 50px;
    margin-bottom: 10px;
    position: relative;
  }
  .folder-item{
    padding: 10px;
    background: white;
    margin-bottom: 10px;
    img{
      width: 40px;
      margin-right: 10px;
    }
  }
</style>